package com.mach.platform.domain.iot;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


/**
 * The persistent class for the iot_dev database table.
 */
@Data
@NoArgsConstructor
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" })
@Entity
@Table(name = "iot_dev")
@NamedQuery(name = "IotDev.findAll", query = "SELECT i FROM IotDev i")
public class IotDev implements Serializable {

	private static final long serialVersionUID = 1L;

	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Id
	private Long id;

	/**
	 * 设备类型
	 */
	@Column(name = "type", columnDefinition = "tinyint default 0")
	private int type;

	/**
	 * 编号
	 */
	private String sn;

	@Column(name = "debug_stat")
	private String debugStat;

	@Column(name = "comm_addr")
	private String commAddr;

	@Transient
	private String temporaryVariable;

	private String name;

	private String pic;

	/**
	 * 排序字段
	 */
	private Float sort;

	@Column(name = "read_interval")
	private Integer readInterval;

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "dev_type_id")
	private IotDevType iotDevType;

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "space_id")
	private IotSpace iotSpace;

	/**
	 * 关联控制流程的数据
	 */
	@OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.LAZY)
	@JoinColumn(name = "ctrl_id")
	private List<IotCtrlProcess> ctrlProcesses = new ArrayList<>();

	@OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.LAZY)
	@JoinColumn(name = "dev_id")
	private List<IotDevParams> devParams = new ArrayList<>();

	@OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.LAZY)
	@JoinColumn(name = "dev_id")
	private List<IotVirtualItem> virtualItems = new ArrayList<>();

	@Column(name = "script", columnDefinition = "TEXT")
	private String script;

	@Column(name = "script_switch", columnDefinition = "tinyint default 0")
	private int scriptSwitch;

	@Transient
	private List<Object> iotCollItemDatas = new ArrayList<>();

	@Transient
	private boolean follow;

	@Transient
	private Integer status;

	public List<IotVirtualItem> getVirtualItems ( ) {

		if (this.virtualItems.size() > 0) {
			for (int i = 0; i < virtualItems.size(); i++) {
				if (virtualItems.get(i).getSort() == null) {
					virtualItems.get(i).setSort(1);
				}
			}
			return virtualItems.stream().sorted(Comparator.comparing(IotVirtualItem::getSort)).collect(Collectors.toList());
		}

		return virtualItems;
	}

}
